<template>
  <div v-loading="loading" class="networks" element-loading-text="加载中...">
    <div class="title_header">
      <div class="line"></div>
      <h4 class="text">售后部门列表</h4>
    </div>
    <div class="line_"></div>
    <div class="main">
      <div>
        <div class="sidebar">
          <div class="header">
            <h4>部门分类</h4>
            <el-space :size="0" :spacer="spacer">
              <HLink v-permission="'network_addType'" @click="addNetworkTypeTypeDialogVisible = true">新增分类</HLink>
              <HLink v-permission="'network_editType'" v-if="!editshow" @click="editshow = !editshow">点击编辑</HLink>
              <HLink v-else @click="editshow = !editshow">点击完成</HLink>
            </el-space>
          </div>
          <div class="line_min"></div>
          <!-- <h4 style="padding: 12px 0;border-bottom: 1px solid #ebeef5;">部门分类</h4> -->
          <div class="trees_container">
            <div
              :class="{ tree_item: true, active_tree_item: !isTypeId }"
              @click="onSelectGoodTypeTree({ id: 0, name: '' }, { level: 0 })"
            >
              {{ dataType[0].name }}</div
            >
            <div class="tree_box">
              <el-tree
                :accordion="true"
                style="max-width: 100%"
                :data="dataType[0].childData"
                :props="defaultProps"
                node-key="id"
                @node-click="onSelectGoodTypeTree"
              >
                <template #default="{ node, data }">
                  <span
                    class="custom-tree-node"
                    :class="{ is_active_tree_item: isTypeId == data.id, is_disable: data.status }"
                  >
                    <span style="height: 100%">
                      <ShowTooltip
                        placement="top"
                        :ref-name="'testName' + node.id"
                        class-name="is_textClass"
                        :content="node.label"
                        :is-text="true"
                        :color="isTypeId == data.id ? '#fff' : data.status ? '#999' : '#666'"
                        :size="12"
                        :offset="5"
                        :show-after="300"
                      ></ShowTooltip>
                    </span>
                    <div
                      v-if="editshow"
                      style="
                        position: absolute;
                        right: 0;
                        display: flex;
                        gap: 8px;
                        z-index: 999;
                        padding-right: 2px;
                      "
                    >
                      <el-icon size="14" @click.stop="onEditGoodType(node, data)">
                        <EditPen />
                      </el-icon>
                      <el-icon size="14" @click.stop="onDelGoodType(node, data)">
                        <Delete />
                      </el-icon>
                    </div>
                  </span>
                </template>
              </el-tree>
            </div>
          </div>
        </div>
      </div>
      <div class="table_list">
        <div class="header">
          <div class="btn_group">
            <router-link to="/net/new">
              <HPlainButton v-permission="'network_add'"> 新增部门 </HPlainButton>
            </router-link>
            <!-- <h-plain-button v-permission="'network_map'" @click="onNetworkMap('add')">部门地图</h-plain-button> -->
            <edit-strategy v-permission="'network_strategy'" :network-ids="ids" @update="getnetworkListRows" />
            <el-dropdown trigger="click">
              <HButton>
                <span>更多</span>
                <el-icon style="margin-left: 5px">
                  <ArrowDown />
                </el-icon>
              </HButton>
              <template #dropdown>
                <el-dropdown-menu>
                  <div v-permission="'network_import'">
                    <el-dropdown-item @click="onNetworkMap('in')"> 导入部门 </el-dropdown-item>
                  </div>
                  <div v-permission="'network_export'">
                    <el-dropdown-item @click="onNetworkMap('out')"> 导出部门 </el-dropdown-item>
                  </div>
                  
                  <div v-permission="'network_changeTeam'">
                    <el-dropdown-item :disabled="ids.length <= 0" @click="changeTeam"
                    >修改团队</el-dropdown-item
                  >
                  </div>
                  
                  <div v-permission="'network_changeType'">
                    <el-dropdown-item :disabled="ids.length <= 0" @click="changeType"
                    >修改分类</el-dropdown-item
                  >
                  </div>
                  <div v-permission="'network_changeAgency'">
                    <el-dropdown-item :disabled="ids.length <= 0" @click="changeNetworkAgency"
                    >修改机构</el-dropdown-item
                  >
                  </div>
                  <div v-permission="'network_enabled'">
                    <el-dropdown-item :disabled="ids.length <= 0" @click="changeAll(1, '启用')">
                    批量启用
                  </el-dropdown-item>
                  </div>
                  <div v-permission="'network_disabled'">
                    <el-dropdown-item :disabled="ids.length <= 0" @click="changeAll(2, '禁用')">
                    批量禁用
                  </el-dropdown-item>
                  </div>
                  <div v-permission="'network_delete'">
                    <el-dropdown-item :disabled="ids.length <= 0" @click="changeAll(3, '删除')">
                    批量删除
                  </el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="search">
            <el-select
              v-model="networkAgencyId"
              placeholder="部门机构"
              clearable
              @change="getnetworkListRows"
            >
              <template #header>
                <div style="display: flex; gap: 10px; align-items: flex-end">
                  <div style="display: flex; flex-direction: column; gap: 10px; width: 160px">
                    <el-input
                      v-model.trim="selectVo.name"
                      clearable
                      placeholder="请输入搜索"
                      @keyup.enter="selecUserFun"
                      @clear="selecUserFun"
                    />
                  </div>
                  <HPlainButton @click="selecUserFun">搜索</HPlainButton>
                </div>
              </template>
              <el-option
                v-for="item in NetworkAgencyList"
                :key="item.name"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
            <el-select
              v-model="status"
              placeholder="部门状态"
              clearable
              @change="getnetworkListRows"
            >
              <el-option
                v-for="item in userStatus"
                :key="item.status"
                :label="item.name"
                :value="item.status"
              />
            </el-select>
            <el-select
              v-model="teamType"
              class="net_category"
              placeholder="团队模式"
              clearable
              @change="getnetworkListRows"
            >
              <el-option
                v-for="item in teamTypeList"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
            <!-- <el-select
            class="net_category"
            v-model="type"
            placeholder="部门类型"
            clearable
            @change="getnetworkListRows"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
            <el-input
              v-model.trim="name"
              placeholder="部门名称/负责人/手机号/所属地址"
              class="keyword"
              clearable
              @keyup.enter="getnetworkListRows"
              @clear="getnetworkListRows"
            />
            <div class="btn_group">
              <HButton type="primary" @click="getnetworkListRows">
                <el-icon class="mr5">
                  <Search />
                </el-icon>
                搜索
              </HButton>
              <HButton @click="onReset">
                <el-icon class="mr5">
                  <RefreshRight />
                </el-icon>
                重置
              </HButton>
            </div>
          </div>
        </div>
        <div class="table">
          <el-table
            :border="true"
            height="100%"
            style="position: absolute"
            stripe
            resizable
            :data="tableDataList"
            @selection-change="handleChange"
            @row-dblclick="goEdit"
          >
            <el-table-column type="selection" width="40" fixed />

            <!-- 序号 -->
            <el-table-column fixed type="index" label="序号" width="49" :align="'center'" />

            <!-- 部门编号 -->
            <el-table-column show-overflow-tooltip prop="code" label="部门编号" width="110" />

            <!-- 部门名称 -->
            <el-table-column show-overflow-tooltip label="部门名称" width="180">
              <template #default="scope">
                <span class="xy_main_btn" @click="goEdit(scope.row)">{{ scope.row.name }}</span>
              </template>
            </el-table-column>

            <!-- 部门简称 -->
            <el-table-column
              show-overflow-tooltip
              prop="shorterName"
              label="部门简称"
              width="110"
            />

            <!-- 部门状态 -->
            <el-table-column
              prop="status"
              label="部门状态"
              width="73"
              fixed="right"
              :align="'center'"
            >
              <template #default="scope">
                <div class="flex_justify_center">
                  <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
                  <HStatus v-else>启用</HStatus>
                </div>
              </template>
            </el-table-column>

            <!-- 团队模式 -->
            <el-table-column prop="teamType" label="团队模式" width="73">
              <template #default="scope">
                <span>{{ scope.row.teamType == 1 ? '团队' : '个人' }}</span>
              </template>
            </el-table-column>

            <!-- 部门分类 -->
            <el-table-column show-overflow-tooltip label="部门分类" width="120">
              <template #default="i">
                {{
                  [i.row.networkType, i.row.twoNetworkType, i.row.threeNetworkType]
                    .filter((o) => o)
                    .join('-')
                }}
              </template>
            </el-table-column>

            <!-- 部门机构 -->
            <!-- <el-table-column
              show-overflow-tooltip
              prop="networkAgency"
              label="部门机构"
              width="120"
            /> -->

            <!-- 接单策略 -->
            <el-table-column prop="autoSureReceiveOrder" label="接单策略" width="97">
              <template #default="scope">
                <span v-if="scope.row.autoSureReceiveOrder">自动确认接单</span>
                <span v-else type="success">人工确认接单</span>
              </template>
            </el-table-column>

            <!-- 全部工单 -->
            <el-table-column
              show-overflow-tooltip
              prop="totalOrderQty"
              label="全部工单"
              width="73"
            />

            <!-- 服务中的工单 -->
            <el-table-column
              show-overflow-tooltip
              prop="serviceOrderQty"
              label="服务中的工单"
              width="97"
            />

            <!-- 部门人数 -->
            <el-table-column show-overflow-tooltip prop="empCount" label="部门人数" width="73" />

            <!-- 部门负责人 -->
            <el-table-column
              show-overflow-tooltip
              prop="managerUserName"
              label="部门负责人"
              width="100"
            />

            <!-- 联系电话 -->
            <el-table-column
              show-overflow-tooltip
              prop="managerUserPhone"
              label="联系电话"
              width="104"
            />

            <!-- 地址 -->
            <el-table-column show-overflow-tooltip label="地址" width="220">
              <template #default="item">
                {{ item.row.province }}{{ item.row.city }}{{ item.row.area }}{{ item.row.town
                }}{{ item.row.address }}
              </template>
            </el-table-column>

            <!-- 创建时间 -->
            <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

            <!-- 更新时间 -->
            <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="pagination"
            :list_total="total"
            @size-change="getnetworkListRows()"
            @current-change="getnetworkListRows(false)"
          />
        </div>
      </div>
    </div>

    <!--部门导出-->
    <h-dialog
      v-model="exportDialog"
      title="部门导出"
      :loading="saveNetworkFieldLoading || saveAndExportNetworkFieldLoading"
      :width="800"
    >
      <div style="display: flex; flex-direction: column; gap: 24px">
        <!-- <el-space direction="vertical" alignment="start">
          <div>条件搜索</div>
          <el-space>
            <el-select style="width: 140px" v-model="category" @change="getnetworkListRows" placeholder="部门模式"
              clearable>
              <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-select v-model="type" placeholder="部门分类" clearable @change="getnetworkListRows" style="width: 140px">
              <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-select style="width: 180px;" @change="getnetworkListRows" placeholder="部门分类" filterable clearable v-model="networkTypeId2">
            <template #header>
              <div class="select_header" style="display: flex;gap: 5px" >
                <el-input v-model="networkTypeKeyword" placeholder="搜索分类名称" style="width: 120px;" @keyup.enter="networkTypeKeywordFun" />
                <h-plain-button @click="networkTypeKeywordFun">搜索</h-plain-button>
              </div>
            </template>
            <el-option v-for="item in netWorktypeOptions" :key="item.name" :value="item.id" :label="item.name" />
          </el-select>
            <el-input placeholder="部门名称/负责人/手机号/所属地址" @keyup.enter="getnetworkListRows" v-model="name" class="w120"
              style="width: 230px" clearable />
          </el-space>
        </el-space> -->
        <!-- 导出字段 -->
        <el-space direction="vertical" alignment="start">
          <el-space>
            <div style="color: #505050">导出字段</div>
            <div style="color: #a6a6a6; font-size: 12px">（拖拽可排序）</div>
            <HLink type="error" @click="handleRemoveAllExportField">清空全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              v-for="(column, index) in exportFields"
              :key="column.value"
              :draggable="true"
              class="export-field-item"
              @dragstart="handleDragStart(index)"
              @dragend="handleDragEnd"
              @dragenter="handleDragEnter(index)"
              @mouseenter="() => (column.showClose = true)"
              @mouseleave="() => (column.showClose = false)"
              @click="handleRemoveFromExportFields(column)"
            >
              <div class="export-field-item-text">{{ column.name }}</div>
              <div class="export-field-item-btn">-</div>
            </div>
          </el-space>
        </el-space>

        <!-- 系统字段 -->
        <el-space direction="vertical" alignment="start">
          <el-space>
            <div style="color: #505050">系统字段</div>
            <div style="color: #a6a6a6; font-size: 12px">（点击添加）</div>
            <HLink type="error" @click="handleAddALLToExportFields(1)">添加全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              v-for="column in sysInitExportFields"
              :key="column.id"
              class="add-field-item"
              @mouseenter="() => (column.showAdd = true)"
              @mouseleave="() => (column.showAdd = false)"
              @click="handleAddToExportFields(column, 1)"
            >
              <div class="add-field-item-text">{{ column.name }}</div>
              <div class="add-field-item-btn">+</div>
            </div>
          </el-space>
        </el-space>

        <!-- 自定义字段 -->
        <el-space direction="vertical" alignment="start">
          <el-space>
            <div style="color: #505050">部门自定义字段</div>
            <div style="color: #a6a6a6; font-size: 12px">（点击添加）</div>
            <HLink type="error" @click="handleAddALLToExportFields(2)">添加全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              v-for="column in customFields"
              :key="column.id"
              class="add-field-item"
              @mouseenter="() => (column.showAdd = true)"
              @mouseleave="() => (column.showAdd = false)"
              @click="handleAddToExportFields(column, 2)"
            >
              <div class="add-field-item-text">{{ column.name }}</div>
              <div class="add-field-item-btn">+</div>
            </div>
          </el-space>
        </el-space>
      </div>
      <template #footer>
        <HButton is-modal type="success" @click="handleSaveAndExportNetworkField"
          >保存并导出</HButton
        >
        <HButton is-modal type="primary" @click="handleSaveNetworkField">保存</HButton>
        <HButton is-modal @click="exportDialog = false">取消</HButton>
      </template>
    </h-dialog>
    <h-dialog
      v-model="teamTypeDialog"
      title="修改团队"
      :loading="updateNetworkTeamTypeLoading"
      @close=";(teamTypeDialog = false), (team = 1)"
    >
      <div class="flex-center">
        <el-radio-group v-model="team">
          <el-radio :value="1" size="large">团队</el-radio>
          <el-radio :value="2" size="large">个人</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <HButton type="primary" is-modal @click="saveTeam">保存</HButton>
        <HButton is-modal @click=";(teamTypeDialog = false), (team = 1)">取消 </HButton>
      </template>
    </h-dialog>
    <!-- 新增/修改  弹窗 -->
    <h-dialog v-model="dialogVisible" :title="typeDialogTitle" :loading="confirmAddGoodTypeLoading">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="ruleForm"
        label-position="top"
        class="modal_form_content"
      >
        <el-form-item v-if="ruleForm.parentId" label="上级分类">
          <el-input v-model.trim="ruleForm.parentName" disabled />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model.trim="ruleForm.name" clearable placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton type="primary" is-modal @click="onConfirmAddGoodType">确定</HButton>
        <HButton is-modal @click="dialogVisible = false"> 取消 </HButton>
      </template>
    </h-dialog>
    <!-- 修改关联分类 -->
    <h-dialog v-model="dialogVisibleType" title="修改部门关联分类" :loading="loadingType">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="networkTypeVo"
        label-position="top"
        class="modal_form_content"
      >
        <el-form-item label="关联分类" prop="networkTypeIds">
          <el-cascader
            v-model="networkTypeVo.networkTypeIds"
            clearable
            :props="CascaderProps"
            :options="dataType[0].childData"
          >
            <template #default="{ node, data }">
              <span>{{ data.name }}</span>
              <span v-if="!node.isLeaf"> ({{ data.childData.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton type="primary" is-modal @click="onConfirmTypeChange">确定</HButton>
        <HButton is-modal @click="dialogVisibleType = false"> 取消 </HButton>
      </template>
    </h-dialog>
    <!-- 修改关联机构 -->
    <h-dialog v-model="dialogVisibleAgency" title="修改部门关联机构" :loading="loadingType">
      <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="networkAgencyVo"
        label-position="top"
        class="modal_form_content"
      >
        <el-form-item label="关联机构" prop="networkAgencyId">
          <el-select
            v-model="networkAgencyVo.networkAgencyId"
            placeholder="请选择部门机构"
            clearable
          >
            <template #header>
              <div style="display: flex; gap: 10px; align-items: flex-end">
                <div style="display: flex; flex-direction: column; gap: 10px; width: 160px">
                  <el-input
                    v-model.trim="selectVo.name"
                    clearable
                    placeholder="请输入搜索"
                    @keyup.enter="selecUserFun"
                    @clear="selecUserFun"
                  />
                </div>
                <HPlainButton @click="selecUserFun">搜索</HPlainButton>
              </div>
            </template>
            <el-option
              v-for="item in NetworkAgencyList"
              :key="item.name"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <HButton type="primary" is-modal @click="onConfirmAgencyChange">确定</HButton>
        <HButton is-modal @click="dialogVisibleAgency = false"> 取消 </HButton>
      </template>
    </h-dialog>

    <AddNetworkType
      v-model:visible="addNetworkTypeTypeDialogVisible"
      type="network"
      @update="getList"
    />

    <UpdateNetworkType
      v-model:visible="updateNetworkTypeDialogVisible"
      type="network"
      :update-type="currentEditNetworkType"
      @update="getList"
    />
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, watch, onMounted, h, reactive } from 'vue'
  import { ArrowDown, RefreshRight, Search } from '@element-plus/icons-vue'
  import { useRouter, useRoute } from 'vue-router'
  import useBatch from './useBatch'
  import { ElMessage, ElDivider, ElMessageBox } from 'element-plus'
  import EditStrategy from './EditStrategy/index.vue'
  import { getTypeList, saveType, deleteType } from '@/api/basic'
  import {
    updateNetworkTeamType,
    getNetworkAgencyList,
    updateNetworkType,
    updateNetworkAgency,
  } from '@/api/network'
  import _ from 'lodash'
  import AddNetworkType from '@/components/pages/common/type/add-type/AddType.vue'
  import UpdateNetworkType from '@/components/pages/common/type/update-type/UpdateType.vue'
  import type Node from 'element-plus/es/components/tree/src/model/node'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.network.networkList,
  })

  // 添加分类弹窗显示状态
  const addNetworkTypeTypeDialogVisible = ref(false)

  // 编辑分类弹窗显示状态
  const updateNetworkTypeDialogVisible = ref(false)

  // 当前正在编辑的分类
  const currentEditNetworkType = ref({
    id: '',
    name: '',
    status: false,
    parentId: '',
    level: 1,
  })

  /**
   * 编辑分类
   */
  const onEditGoodType = (node: Node, d) => {
    currentEditNetworkType.value = {
      id: d.id,
      status: d.status,
      name: d.name,
      parentId: node.parent.data.id || '0',
      level: d.level,
    }
    updateNetworkTypeDialogVisible.value = true
  }

  let {
    loading,
    changeAll,
    ids,
    getnetworkListRows,
    networkTypeId,
    getNetworkExportFieldList,
    getNetworkSysInitExportFieldList,
    getNetworkCustomFieldList,
    networkTypeKeyword,
    pagination,
    total,
    category,
    type,
    status,
    tableDataList,
    name,
    exportFields,
    sysInitExportFields,
    customFields,
    teamType,
    saveNetworkFieldLoading,
    saveAndExportNetworkFieldLoading,
    handleChange,
    handleSaveAndExportNetworkField,
    handleAddToExportFields,
    handleRemoveFromExportFields,
    handleRemoveAllExportField,
    handleSaveNetworkField,
    handleAddALLToExportFields,
    twoNetworkTypeId,
    threeNetworkTypeId,
    networkAgencyId,
  } = useBatch()
  const router = useRouter()
  const route = useRoute()
  const exportDialog = ref(false)
  // 部门编辑
  const goEdit = (n: { id: string }) => {
    router.push('/net/netdetail/' + n.id)
  }
  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const userStatus = ref([
    // 公司状态
    { status: 0, name: '启用' },
    { status: 1, name: '禁用' },
  ])

  const isTypeId = ref()
  const isTypeName = ref('')
  const isLevel = ref(1)
  const onSelectGoodTypeTree = (d, n) => {
    if (d.status) return
    category.value = null
    type.value = null
    name.value = ''
    teamType.value = null
    networkTypeKeyword.value = ''
    status.value = null
    networkAgencyId.value = ''
    twoNetworkTypeId.value = ''
    threeNetworkTypeId.value = ''
    networkTypeId.value = null
    isTypeId.value = d.id
    isTypeName.value = d.name
    isLevel.value = n.level
    switch (n.level) {
      case 1:
        networkTypeId.value = d.id

        break
      case 2:
        networkTypeId.value = n.parent.data.id
        twoNetworkTypeId.value = d.id

        break
      case 3:
        networkTypeId.value = n.parent.parent.data.id
        twoNetworkTypeId.value = n.parent.data.id
        threeNetworkTypeId.value = d.id
        break
      default:
        break
    }
    getnetworkListRows()
  }
  // 获取部门机构
  const selectVo = ref({
    limit: 0,
    name: '',
    page: 0,
  })
  const NetworkAgencyList = ref([])
  const getNetworkAgencyListFun = async () => {
    await getNetworkAgencyList(selectVo.value).then((res) => {
      if (res.data.code == 20000) {
        NetworkAgencyList.value = res.data.data.rows
      }
    })
  }
  const selecUserFun = _.debounce(() => {
    getNetworkAgencyListFun()
  }, 400)
  const dialogVisible = ref(false)
  const edit = ref(false)
  const typeDialogTitle = ref('') // 新增/修改类别弹窗标题
  // 表单数据
  const ruleForm = reactive({
    id: '',
    name: '',
    parentId: '',
    parentName: '',
  })
  const editshow = ref(false)
  const ruleFormRef = ref(null)
  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
    networkTypeIds: [{ required: true, message: '请选择关联分类', trigger: ['blur', 'change'] }],
    networkAgencyId: [{ required: true, message: '请选择关联机构', trigger: ['blur', 'change'] }],
  })
  const confirmAddGoodTypeLoading = ref(false)
  const onConfirmAddGoodType = () => {
    if (!ruleFormRef.value) return
    const data = {
      name: ruleForm.name,
      parentId: ruleForm.parentId,
      status: false,
    }
    const data2 = {
      id: ruleForm.id,
      name: ruleForm.name,
      parentId: ruleForm.parentId,
      status: false,
    }
    ruleFormRef.value
      .validate()
      .then(async () => {
        confirmAddGoodTypeLoading.value = true
        if (typeDialogTitle.value == '添加分类') {
          await saveTypeData(data, saveType, dialogVisible, getList)
        } else {
          await saveTypeData(data2, saveType, dialogVisible, getList)
        }
        confirmAddGoodTypeLoading.value = false
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起报错
      })
  }
  // 封装保存数据的方法
  const saveTypeData = async (data, method, dialog, getFilter) => {
    const res = await method(data)
    if (res.data.success == true) {
      if (!edit.value) {
        ElMessageBox({
          type: 'success',
          message: '分类添加成功，是否立即为新分类关联部门？',
          showCancelButton: true,
          confirmButtonText: '是',
          cancelButtonText: '否',
        }).then(() => {
          router.push({
            path: '/net/new',
            query: { typeName: ruleForm.name, parentId: ruleForm.parentId },
          })
        })
      } else {
        ElMessage({
          message: res.data.message,
          type: 'success',
          plain: true,
          showClose: true,
        })
      }
      dialog.value = false
      getFilter()
    } else {
      ElMessage({
        message: res.data.message,
        type: 'warning',
        plain: true,
        showClose: true,
      })
      return
    }
  }

  const onDelGoodType = (n, d) => {
    ruleForm.id = d.id
    ElMessageBox({
      type: 'error',
      title: '提示',
      message: `确定要删除"${d.name}"该分类吗？`,
      showCancelButton: true,
    })
      .then(() => {
        deleteType([ruleForm.id]).then((res) => {
          if (res.data.code == 20000) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              plain: true,
              duration: 5000,
              showClose: true,
            })
            getList()
            onReset()
          }
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起eslint的报错
      })
  }

  const defaultProps = {
    children: 'childData',
    label: 'name',
    disabled: 'status',
  }
  const dataType = ref([
    {
      id: 0,
      name: '全部',
      childData: [],
    },
  ])
  // 获取列表数据
  const getList = async () => {
    loading.value = true
    await getTypeList().then((res) => {
      dataType.value[0].childData = res.data.data.rows
    })
    loading.value = false
  }

  onMounted(() => {
    getList()
    getNetworkAgencyListFun()
  })

  const onNetworkMap = async (val) => {
    switch (val) {
      case 'add':
        ElMessage({
          type: 'success',
          message: '正在升级维护中，敬请期待...',
          showClose: true,
          plain: true,
          duration: 5000,
        })
        break
      case 'out':
        await getNetworkExportFieldList()
        await getNetworkSysInitExportFieldList()
        await getNetworkCustomFieldList()
        exportFields.value.forEach((column) => {
          if (column.type === 1) {
            const index = sysInitExportFields.value.findIndex((item) => item.code === column.value)
            sysInitExportFields.value.splice(index, 1)
          } else if (column.type === 2) {
            const index = customFields.value.findIndex((item) => item.id === column.value)
            customFields.value.splice(index, 1)
          }
        })

        exportDialog.value = true
        break
      case 'in':
        router.push('/net/networkImport')
        break
    }
  }

  const teamTypeList = ref([
    { text: '团队', value: 1 },

    { text: '个人', value: 2 },
  ])
  const team = ref(1)
  const teamTypeDialog = ref(false)
  const changeTeam = () => {
    teamTypeDialog.value = true
  }

  const updateNetworkTeamTypeLoading = ref(false)

  // 保存团队修改
  const saveTeam = () => {
    updateNetworkTeamTypeLoading.value = true
    updateNetworkTeamType(ids.value, team.value).then((res) => {
      updateNetworkTeamTypeLoading.value = false
      if (res.data.code == 20000) {
        teamTypeDialog.value = false
        ids.value = []
        getnetworkListRows()
      }
      if (res.data.isError || res.data.code === 61000)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 5000,
          plain: true,
        })
    })
  }
  // ****************修改关联分类**************
  const CascaderProps = ref({
    value: 'id',
    label: 'name',
    children: 'childData',
    checkStrictly: true,
    disabled: 'status',
  })
  const dialogVisibleType = ref(false)
  const changeType = () => {
    networkTypeVo.value.networkTypeIds = []
    dialogVisibleType.value = true
  }
  const loadingType = ref(false)
  const networkTypeVo = ref({
    networkIdList: [],
    oneNetworkType: '',
    oneNetworkTypeId: '',
    threeNetworkType: '',
    threeNetworkTypeId: '',
    twoNetworkType: '',
    twoNetworkTypeId: '',
    networkTypeIds: [],
  })
  const onConfirmTypeChange = () => {
    ruleFormRef.value
      .validate()
      .then(async () => {
        loadingType.value = true
        networkTypeVo.value = {
          ...networkTypeVo.value,
          networkIdList: [],
          oneNetworkType: '',
          oneNetworkTypeId: '',
          threeNetworkType: '',
          threeNetworkTypeId: '',
          twoNetworkType: '',
          twoNetworkTypeId: '',
        }
        networkTypeVo.value.networkIdList = ids.value
        dataType.value[0].childData.forEach((item) => {
          if (networkTypeVo.value.networkTypeIds.includes(item.id)) {
            networkTypeVo.value.oneNetworkTypeId = item.id
            networkTypeVo.value.oneNetworkType = item.name
            if (item.childData.length > 0) {
              item.childData.map((item2) => {
                if (networkTypeVo.value.networkTypeIds.includes(item2.id)) {
                  networkTypeVo.value.twoNetworkTypeId = item2.id
                  networkTypeVo.value.twoNetworkType = item2.name
                  if (item2.childData.length > 0) {
                    item2.childData.map((item3) => {
                      if (networkTypeVo.value.networkTypeIds.includes(item3.id)) {
                        networkTypeVo.value.threeNetworkTypeId = item3.id
                        networkTypeVo.value.threeNetworkType = item3.name
                      }
                    })
                  }
                }
              })
            }
          }
        })
        const dataTypeVo = _.cloneDeep(networkTypeVo.value)
        delete dataTypeVo.networkTypeIds
        updateNetworkType(dataTypeVo).then((res) => {
          if (res.data.code == 20000) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              plain: true,
              showClose: true,
            })
            dialogVisibleType.value = false
            getnetworkListRows()
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              plain: true,
              showClose: true,
            })
          }
          loadingType.value = false
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起eslint的报错
      })
  }
  // *********************修改关联分类 end***************
  // *************修改关联机构********************
  const networkAgencyVo = ref({
    networkAgencyId: '',
    networkIdList: [],
  })
  const dialogVisibleAgency = ref(false)
  const changeNetworkAgency = () => {
    networkAgencyVo.value.networkAgencyId = ''
    dialogVisibleAgency.value = true
  }
  const onConfirmAgencyChange = () => {
    ruleFormRef.value
      .validate()
      .then(async () => {
        loadingType.value = true
        networkAgencyVo.value.networkIdList = ids.value
        updateNetworkAgency(networkAgencyVo.value).then((res) => {
          if (res.data.code == 20000) {
            ElMessage({
              message: res.data.message,
              type: 'success',
              plain: true,
              showClose: true,
            })
            dialogVisibleAgency.value = false
            getnetworkListRows()
          } else {
            ElMessage({
              message: res.data.message,
              type: 'error',
              plain: true,
              showClose: true,
            })
          }
          loadingType.value = false
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起eslint的报错
      })
  }
  // *************修改关联机构 end*************
  // 拖拽的元素的索引
  const moveIndex = ref(-1)

  // 目标位置
  const targetIndex = ref(-1)

  // 拖拽开始事件
  const handleDragStart = (index: number) => {
    moveIndex.value = index
  }

  // 拖拽结束事件
  const handleDragEnd = () => {
    const moveItem = exportFields.value[moveIndex.value]
    const targetItem = exportFields.value[targetIndex.value]
    exportFields.value.splice(moveIndex.value, 1, targetItem)
    exportFields.value.splice(targetIndex.value, 1, moveItem)
  }

  // 当拖动的元素进入到当前元素时触发
  const handleDragEnter = (index: number) => {
    targetIndex.value = index
  }

  // 重置事件
  const onReset = () => {
    category.value = null
    type.value = null
    name.value = ''
    teamType.value = null
    networkTypeKeyword.value = ''
    status.value = null
    networkAgencyId.value = ''
    twoNetworkTypeId.value = ''
    threeNetworkTypeId.value = ''
    networkTypeId.value = null
    isTypeId.value = ''
    isTypeName.value = ''
    isLevel.value = null
    getnetworkListRows()
  }

  watch(route, (value) => {
    if (value.name === 'netList') {
      getnetworkListRows()
    }
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
